package com.wuseguang.springcloud.service.impl;


import com.wuseguang.springcloud.dao.jdbc.RolesJdbc;
import com.wuseguang.springcloud.dao.mapper.RolesMapper;
import com.wuseguang.springcloud.dao.repository.GroupingJurisdictiondRepository;
import com.wuseguang.springcloud.dao.repository.GroupingRepository;
import com.wuseguang.springcloud.dao.repository.RolesRepository;
import com.wuseguang.springcloud.entity.Grouping;
import com.wuseguang.springcloud.entity.GroupingJurisdiction;
import com.wuseguang.springcloud.entity.Roles;
import com.wuseguang.springcloud.service.RolesService;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.PaginationUtil;
import com.wuseguang.springcloud.util.PagingTool;
import com.wuseguang.springcloud.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author zmc
 * @since 2019-11-27
 */
@Service
public class RolesServiceImpl implements RolesService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RolesRepository rolesRepository;
    @Autowired
    private RolesMapper rolesMapper;
    @Autowired
    private RolesJdbc rolesJdbc;
    @Autowired
    private GroupingJurisdictiondRepository groupingJurisdictiondRepository;
    @Autowired
    private GroupingRepository groupingRepository;

    @Override
    public Result findSchoolRoles(String schoolId, Integer type) {

        logger.info("查询角色信息");

        String sql = "select id,name  from `roles` WHERE `school_id` in (?,0) and `type` =?";
        logger.info("查询角色信息 sql = {}",sql);
        List<Map<String,Object>> list =rolesJdbc.queryListMap(sql ,schoolId,type);

        return new Result(list);
    }

    @Override
    public Result findRolePermissions(String schoolId, Integer indexNo, Integer rows) {

        logger.info("查询角色权限：RolesServiceImpl.class -> findRolePermissions");

        //查询角色组
        String sql = "select * from grouping where school_id  in (0,?)";
        List<Map<String, Object>> groupingList = rolesJdbc.queryListMap(sql, schoolId);


        for (Map<String, Object> groupingMap : groupingList) {
            //查询角色
            sql = "select r.id,r.name,r.school_id,r.grouping_id from roles r where   r.grouping_id=? and r.type =1 and school_id in (0,?)";
            //查询角色
            List<Map<String, Object>> roleList = rolesJdbc.queryListMap(sql, groupingMap.get("id"), schoolId);
            //循环学校所有角色
            for (Map<String, Object> role : roleList) {
                //查询角色下面的所有教师
                sql = "SELECT id,name  FROM  teacher t where   EXISTS " +
                        "( SELECT * FROM teacher_role tr WHERE t.id = tr.teacher_id AND tr.role_id = ? and school_id =? GROUP BY tr.teacher_id )";
                //角色下面的教师集合
                List<Map<String, Object>> teacherList = rolesJdbc.queryListMap(sql, role.get("id"), schoolId);
                //把教师放进角色里
                role.put("list", teacherList);
            }
            groupingMap.put("list", roleList);
        }


        //创建分页工具
        PagingTool tool = new PagingTool();
        //放入页码
        tool.setIndexNo(indexNo);
        //放入每页显示数量
        tool.setRows(rows);
        //放入角色集合
        tool.setList(groupingList);
        //返回数据
        return new Result(new PaginationUtil<>(groupingList.size(), rows, tool.getList(), indexNo));
    }

    @Override
    public Result findRoleFunction(Integer roleId, String schoolId) {

        logger.info("查询角色功能权限：RolesServiceImpl.class -> findRoleFunction");
        //角色的功能权限
        List<Map<String, Object>> function = rolesJdbc.findRoleFunction(roleId, schoolId);

        return new Result(function);
    }

    @Override
    public Result addAndDeleteRoleJurisdiction(Integer groupingId, Integer[] jurisdictionId, String schoolId) {

        logger.info("给角色添加权限：RolesServiceImpl.class -> addRoleJurisdiction");
        logger.info("角色组id = {}", groupingId);
        logger.info("权限id = {}", jurisdictionId);


        //查询这个学校的所有权限
        String sql = "select jurisdiction_id id,CONCAT(CONVERT(jurisdiction_id,CHAR),'-',CONVERT(jurisdiction_pid,CHAR),'-',jurisdiction_name) name from school_jurisdiction where school_id = ?";
        //权限map
        Map<String, Object> map = rolesJdbc.queryIdMap(sql, "id", "name", schoolId);
        //角色的所有权限
        List<GroupingJurisdiction> list = new ArrayList<>();


        sql = "DELETE FROM `grouping_jurisdiction` WHERE grouping_id = ? and school_id =? ";
        logger.info("先删除这个学校这个角色组的所有功能权限 SQL = {}", sql);
        int result = rolesJdbc.updateByParameter(sql, groupingId, schoolId);
        logger.info("删除结果 result = {}", result);


        //循环权限id
        for (int i = 0; i < jurisdictionId.length; i++) {
            String[] jurisdiction = map.get(jurisdictionId[i].toString()).toString().split("-");
            GroupingJurisdiction rj = new GroupingJurisdiction();
            rj.setSchoolId(Integer.valueOf(schoolId));
            rj.setJurisdictionId(Integer.valueOf(jurisdiction[0]));
            rj.setJurisdictionPid(Integer.valueOf(jurisdiction[1]));
            rj.setJurisdictionName(jurisdiction[2]);
            rj.setGroupingId(groupingId);
            list.add(rj);
        }


        //批量添加
        groupingJurisdictiondRepository.saveAll(list);
        return new Result();
    }

    @Override
    public Result updateRoleName(Integer roleId, String name, Integer schoolId) {
        logger.info("修改角色名称：RolesServiceImpl.class -> updateRoleName");
        logger.info("角色id = {},name = {}", roleId, name);

        //查询角色是否已存在
        String sql = "select count(1) count from roles where name =? and school_id = ?";
        int count = rolesJdbc.queryCount(sql, name, schoolId);
        //判断是否已经存在
        if (count > 0) {
            return new Result(CodeUtil.ROLE_ALREADY_EXISTS);
        }

        //修改角色名称
        sql = "UPDATE `roles` SET `name` = ? WHERE `id` = ? ";
        logger.info("修改角色名称SQL = {},参数 name = {},id = {}", sql, name, roleId);
        int result = rolesJdbc.updateByParameter(sql, name, roleId);
        if (result == 0) {
            return new Result(CodeUtil.ROLE_MODIFICATION_FAILED);
        }
        return new Result();
    }

    @Override
    public Result deleteRole(Integer roleId) {
        logger.info("删除角色：RolesServiceImpl.class -> deleteRole");
        logger.info("角色id = {}", roleId);

        try {
            rolesRepository.deleteById(roleId);
        } catch (Exception e) {

        }
        return new Result();
    }

    @Override
    public Result addRole(Roles roles) {

        logger.info("添加角色：RolesServiceImpl.class -> addRole");

        //查询角色是否已存在
        String sql = "select count(1) count from roles where name =? and school_id = ?";
        int count = rolesJdbc.queryCount(sql, roles.getName(), roles.getSchoolId());
        //判断是否已经存在
        if (count > 0) {
            return new Result(CodeUtil.ROLE_ALREADY_EXISTS);
        }

        //判断如果角色组id为空
        if (StringUtils.isEmpty(roles.getGroupingId())) {
            Grouping g = new Grouping();
            g.setName(roles.getGroupingName());
            g.setSchoolId(roles.getSchoolId());
            //添加组在添加信息
            Integer id = groupingRepository.save(g).getId();
            roles.setGroupingId(id);
        }
        //教师角色
        roles.setType(1);
        rolesRepository.save(roles);

        return new Result();
    }


    @Override
    public Result findDepartmentTeacher(String schoolId) {
        logger.info("查询角色权限：RolesServiceImpl.class -> findRolePermissions");

        //查询角色组
        String sql = "select * from grouping where school_id  in (0,?)";
        List<Map<String, Object>> groupingList = rolesJdbc.queryListMap(sql, schoolId);


        for (Map<String, Object> groupingMap : groupingList) {
            //查询角色
            sql = "select r.id,r.name,r.school_id,r.grouping_id from roles r where   r.grouping_id=? and r.type =1 and school_id in (0,?)";
            //查询角色
            List<Map<String, Object>> roleList = rolesJdbc.queryListMap(sql, groupingMap.get("id"), schoolId);
            //循环学校所有角色
            for (Map<String, Object> role : roleList) {
                //查询角色下面的所有教师
                sql = "SELECT id,name  FROM  teacher t where   EXISTS " +
                        "( SELECT * FROM teacher_role tr WHERE t.id = tr.teacher_id AND tr.role_id = ? and school_id =? GROUP BY tr.teacher_id )";
                //角色下面的教师集合
                List<Map<String, Object>> teacherList = rolesJdbc.queryListMap(sql, role.get("id"), schoolId);
                //把教师放进角色里
                role.put("list", teacherList);
            }
            groupingMap.put("list", roleList);
        }

        return new Result(groupingList);
    }
}
